<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <h2 class="login-title">慈善项目管理系统</h2>
      </template>
      <el-form :model="loginForm" :rules="rules" ref="loginFormRef" class="login-form">
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="用户名"
            prefix-icon="User"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="密码"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        <el-form-item prop="captcha">
          <div class="captcha-container">
            <el-input
              v-model="loginForm.captcha"
              placeholder="验证码"
              prefix-icon="Key"
            />
            <img
              :src="captchaUrl"
              class="captcha-image"
              @click="refreshCaptcha"
              alt="验证码"
            />
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" class="login-button" @click="handleLogin">
            登录
          </el-button>
        </el-form-item>
        <div class="login-links">
          <el-link type="primary" @click="handleForgotPassword">忘记密码？</el-link>
          <!-- <div class="register-link">
            <span>还没有账号？</span>
            <el-link type="primary" @click="handleRegister">立即注册</el-link>
          </div> -->
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const loginFormRef = ref<FormInstance>()
const loading = ref(false)
const captchaUrl = ref('')

const loginForm = reactive({
  username: '',
  password: '',
  captcha: ''
})

const rules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 4, max: 4, message: '验证码长度为4位', trigger: 'blur' }
  ]
}

const refreshCaptcha = async () => {
  try {
    const response = await axios.get('/api/auth/captcha')
    if (response.data && response.data.image) {
      captchaUrl.value = response.data.image
      // 保存sessionId用于后续验证
      localStorage.setItem('sessionId', response.data.sessionId)
    }
  } catch (error) {
    ElMessage.error('获取验证码失败')
  }
}

const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  await loginFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      loading.value = true
      try {
        const sessionId = localStorage.getItem('sessionId')
        const response = await axios.post('/api/admin/login', {
          username: loginForm.username,
          password: loginForm.password,
          captcha: loginForm.captcha,
          sessionId: sessionId
        })
        
        if (response.data.token) {
          console.log(response)
          const userStore = useUserStore()
          userStore.loginSuccess({
            token: response.data.token,
            userInfo: {
              username: response.data.data.nickname,
              role: 'admin'
            }
          })
          ElMessage.success('登录成功')
          router.push('/admin/')
        } else {
          ElMessage.error('登录失败：' + response.data.message)
          refreshCaptcha()
        }
      } catch (error) {
        ElMessage.error('登录失败，请稍后重试')
        refreshCaptcha()
      } finally {
        loading.value = false
      }
    }
  })
}

const handleForgotPassword = () => {
  router.push('/forgot-password')
}

// const handleRegister = () => {
//   router.push('/admin/register')
// }

onMounted(() => {
  refreshCaptcha()
})
</script>

<style lang="scss" scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f0f2f5;
}

.login-card {
  width: 400px;
  
  .login-title {
    text-align: center;
    margin: 0;
    color: #303133;
  }
}

.login-form {
  margin-top: 20px;
  
  .login-button {
    width: 100%;
  }

  .captcha-container {
    display: flex;
    gap: 12px;
    
    .el-input {
      flex: 1;
    }
    
    .captcha-image {
      height: 32px;
      cursor: pointer;
    }
  }
  
  .login-links {
    margin-top: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .register-link {
      span {
        color: #606266;
        margin-right: 8px;
      }
    }
  }
}
</style>